//
//  WmcTeamCloudCategriesAlbumVC.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/16.
//

import MJRefresh
import UIKit

extension WmcTeamCloudCategriesAlbumVC: WmcVMProtocol {
    typealias VMType = WmcTeamCloudCategriesAlbumVM
}

class WmcTeamCloudCategriesAlbumVC: WmcBaseVC, WmcStatefulViewController {
    // Lifecycle

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupInitialViewState()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        refresh()

        loadingView = WmcLoadingView()
        emptyView = WmcEEmptyView()
        let errView = WmcErrorView()
        errView.refreshClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.refresh()
        }
        errorView = errView
    }

    // Internal

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "分类相册"

        view.backgroundColor = UIColor.wmc_gray_F7F8FA

        addNaviLineView()
        naviLineView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
        }

        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(self.naviLineView.snp.bottom).offset(8)
            make.left.right.bottom.equalToSuperview()
        }
        WmcNotificationManager.shared.addObserver(type: .deletePhotoSucceed) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.refresh()
        }
    }

    override func bindViewAction() {
        collectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.refresh()
        })
        NotificationCenter.default.addObserver(self, selector: #selector(photoAlbumDataDidChange(notification:)), name: NSNotification.Name(rawValue: "com.watermark.cloudAlbumDataDidChange"), object: nil)
    }

    @objc
    func photoAlbumDataDidChange(notification _: Notification) {
        refresh()
    }

    // Private

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let width = (self.view.bounds.width - 48) / 2.0
        let height = width + 50
        layout.itemSize = CGSize(width: width, height: height)
        layout.minimumLineSpacing = 16
        layout.minimumInteritemSpacing = 16
        layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        layout.sectionHeadersPinToVisibleBounds = true

        let collectView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectView.backgroundColor = .wmc_white_FFFFFF
        collectView.delegate = self
        collectView.dataSource = self
        collectView.showsVerticalScrollIndicator = true
        collectView.register(WmcCloudClassifyAlbumCell.self, forCellWithReuseIdentifier: "WmcCloudClassifyAlbumCell")
        return collectView
    }()

    private lazy var line: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH15_E6E6E6.withAlphaComponent(0.5)
        return view
    }()

    private func refresh() {
        WmcHudManager.loading()
        startLoading()
        viewModel.fetchList { [weak self] _ in
            WmcHudManager.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.collectionView.reloadData()
            weakSelf.collectionView.mj_header?.endRefreshing()
            weakSelf.endLoading()
        } failure: { [weak self] error in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
            weakSelf.endLoading(animated: true, error: error) {
                print(error as Any)
            }
        }
    }
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource

extension WmcTeamCloudCategriesAlbumVC: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return viewModel.dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WmcCloudClassifyAlbumCell", for: indexPath) as! WmcCloudClassifyAlbumCell
        if let model = viewModel.dataSource.yp.object(at: indexPath.row) {
            cell.bindModel(model)
        }
        return cell
    }

    func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let model = viewModel.dataSource.yp.object(at: indexPath.row) else { return }

        if model.typeEnum() == .allPhoto {
            let vm = WmcTeamAlbumAllPhotosVM()
            vm.title = model.title
            vm.type = .allPhoto
            vm.teamAblum = viewModel.teamAblum
            vm.dataNeedUpdate = { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.refresh()
            }
            WmcNavigatorManager.push(.teamAlbumAllPhotos, parms: vm)?.hidesBottomBarWhenPushed = true
        } else if model.typeEnum() == .watermarkPhoto {
            let vm = WmcTeamWatermarkCategoriesVM()
            vm.title = model.title
            vm.teamAblum = viewModel.teamAblum
            WmcNavigatorManager.push(.teamCloudAlbumWatermarkCategory, parms: vm)?.hidesBottomBarWhenPushed = true

        } else if model.typeEnum() == .teamMember {
            let vm = WmcTeamMemberAlbumListVM()
            vm.title = "成员照片"
            vm.teamAblum = viewModel.teamAblum
            WmcNavigatorManager.push(.teamClouldAlbumMemberCategory, parms: vm)?.hidesBottomBarWhenPushed = true
        }
    }
}

extension WmcTeamCloudCategriesAlbumVC {
    func hasContent() -> Bool {
        return viewModel.dataSource.count > 0
    }

    func handleErrorWhenContentAvailable(_ error: Error) {
        /// 处理错误
        print(error)
    }
}
